package de.tum.icuproject.persistence.couchdb;

import com.google.gson.Gson;

import de.tum.icuproject.Subscriber;
import de.tum.icuproject.model.Session;
import de.tum.icuproject.persistence.SessionRepository;
import de.tum.icuproject.persistence.couchdb.insert.InsertRequestHandler;
import de.tum.icuproject.persistence.couchdb.select.IdGeneratorRequestHandler;
import de.tum.icuproject.persistence.couchdb.select.SelectRequestHandler;
import de.tum.icuproject.persistence.couchdb.select.SelectSessionRequestHandler;
import de.tum.icuproject.persistence.couchdb.select.SessionIdGeneratorRequestHandler;

/**
 * Implementation with CouchDB database
 * @author stefanoturchetta
 *
 */
public class SessionRepositoryImpl implements SessionRepository {

	private Subscriber subscriber;

	public SessionRepositoryImpl(Subscriber subscriber) {
		this.subscriber = subscriber;
	}

	@Override
	public void findByPlayerIdAndActivityId(int playerId, int activityId) {
		String requestUrl = "sessions/_design/sessions/_view/by_playerId_activityId?key=[" +
				playerId + "," + activityId + "]";
		SelectRequestHandler select = new SelectSessionRequestHandler(this.subscriber);
		select.execute(requestUrl);
	}

	@Override
	public void insert(Session session) {
		String requestUrl = "sessions";
		String jsonData = new Gson().toJson(session, Session.class);
		InsertRequestHandler insert = new InsertRequestHandler(this.subscriber);
		insert.execute(requestUrl, jsonData);
	}

	@Override
	public void generateSessionId(int playerId, int activityId) {
		// get the last used id
		String requestUrl = "sessions/_design/sessions/_view/by_playerId_activityId?key=[" +
				playerId + "," + activityId + "]&descending=true&limit=1";
		IdGeneratorRequestHandler idGenerator = new SessionIdGeneratorRequestHandler(this.subscriber);
		idGenerator.execute(requestUrl);
	}

}
